package com.ruoyi.web.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.domain.SmsSendDetail;
import com.ruoyi.web.enums.SmsSendDetailEnum;
import com.ruoyi.web.mapper.SmsSendDetailMapper;
import com.ruoyi.web.mapper.SmsSendRecordMapper;
import com.ruoyi.web.service.ISmsSendDetailService;
import com.twilio.rest.api.v2010.account.Message;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 短信发送明细Service业务层处理
 *
 * @date 2023-03-28
 */
@Slf4j
@Service
@AllArgsConstructor
public class SmsSendDetailServiceImpl implements ISmsSendDetailService {
    private final SmsSendDetailMapper smsSendDetailMapper;
    private final SmsSendRecordMapper smsSendRecordMapper;

    /**
     * 查询短信发送明细
     *
     * @param id 短信发送明细主键
     * @return 短信发送明细
     */
    @Override
    public SmsSendDetail selectSmsSendDetailById(Long id) {
        return smsSendDetailMapper.selectSmsSendDetailById(id);
    }

    /**
     * 查询短信发送明细列表
     *
     * @param smsSendDetail 短信发送明细
     * @return 短信发送明细
     */
    @Override
    public List<SmsSendDetail> selectSmsSendDetailList(SmsSendDetail smsSendDetail) {
        List<SmsSendDetail> list = smsSendDetailMapper.selectSmsSendDetailList(smsSendDetail);

        // 遍历
        list.forEach(i -> {
            // 翻译字典项
            i.setStatus(SmsSendDetailEnum.Status.findName(i.getStatus()));
        });

        return list;
    }

    /**
     * 新增短信发送明细
     *
     * @param smsSendDetail 短信发送明细
     * @return 结果
     */
    @Override
    public int insertSmsSendDetail(SmsSendDetail smsSendDetail) {
        smsSendDetail.setCreateTime(DateUtils.getNowDate());
        return smsSendDetailMapper.insertSmsSendDetail(smsSendDetail);
    }

    /**
     * 修改短信发送明细
     *
     * @param smsSendDetail 短信发送明细
     * @return 结果
     */
    @Override
    public int updateSmsSendDetail(SmsSendDetail smsSendDetail) {
        smsSendDetail.setUpdateTime(DateUtils.getNowDate());
        return smsSendDetailMapper.updateSmsSendDetail(smsSendDetail);
    }

    /**
     * 批量删除短信发送明细
     *
     * @param ids 需要删除的短信发送明细主键
     * @return 结果
     */
    @Override
    public int deleteSmsSendDetailByIds(Long[] ids) {
        return smsSendDetailMapper.deleteSmsSendDetailByIds(ids);
    }

    /**
     * 删除短信发送明细信息
     *
     * @param id 短信发送明细主键
     * @return 结果
     */
    @Override
    public int deleteSmsSendDetailById(Long id) {
        return smsSendDetailMapper.deleteSmsSendDetailById(id);
    }

    /**
     * Twilio 消息状态变化通知
     *
     * @param map map
     * @since 2023/4/3 20:31
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void statusNotify(Map<String, String> map) {
        String smsId = map.get("SmsSid");
        String smsStatus = map.get("SmsStatus");
        if (Strings.isBlank(smsId) || Strings.isBlank(smsStatus)) {
            return;
        }

        SmsSendDetail detail = smsSendDetailMapper.getOneLock(smsId);
        if (Objects.isNull(detail) || detail.getStatus().equals(smsStatus)) {
            return;
        }

        detail.setStatus(smsStatus);
        detail.setUpdateTime(new Date());
        if (Message.Status.FAILED.toString().equals(smsStatus)) {
            detail.setRemark("errorCode：" + map.get("ErrorCode"));
        }

        if (smsSendDetailMapper.updateSmsSendDetail(detail) != 1
                // 如果是已完成，增加发送短信记录成功数量
                || Message.Status.DELIVERED.toString().equals(smsStatus)
                && smsSendRecordMapper.incrSuccessNum(detail.getRecordId()) != 1) {
            throw new TadpoleException("Twilio状态修改回调，修改发送短信明细失败，数据：" + map);
        }
    }
}
